package com.ruoyi.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.DeletedConstants;
import com.ruoyi.common.core.constant.MqConstants;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.user.api.domain.UcenterMember;
import com.ruoyi.user.api.domain.dto.UcenterPwdDto;
import com.ruoyi.user.mapper.UcenterMemberMapper;
import com.ruoyi.user.service.IUcenterMemberService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 会员Service业务层处理
 *
 * @author isahino
 * @date 2023-09-21
 */
@Service
public class UcenterMemberServiceImpl extends ServiceImpl<UcenterMemberMapper, UcenterMember> implements IUcenterMemberService {
    @Resource
    private UcenterMemberMapper ucenterMemberMapper;

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 查询会员
     *
     * @param id 会员主键
     * @return 会员
     */
    @Override
    public UcenterMember selectUcenterMemberById(String id) {
        return ucenterMemberMapper.selectUcenterMemberById(id);
    }

    /**
     * 查询会员列表
     *
     * @param ucenterMember 会员
     * @return 会员
     */
    @Override
    public List<UcenterMember> selectUcenterMemberList(UcenterMember ucenterMember) {
        return ucenterMemberMapper.selectUcenterMemberList(ucenterMember);
    }

    /**
     * 新增会员
     *
     * @param ucenterMember 会员
     * @return 结果
     */
    @Override
    public int insertUcenterMember(UcenterMember ucenterMember) {
        return ucenterMemberMapper.insert(ucenterMember);
    }

    /**
     * 修改会员
     *
     * @param ucenterMember 会员
     * @return 结果
     */
    @Override
    public int updateUcenterMember(UcenterMember ucenterMember) {
        return ucenterMemberMapper.updateById(ucenterMember);
    }

    /**
     * 批量删除会员
     *
     * @param ids 需要删除的会员主键
     * @return 结果
     */
    @Override
    public int deleteUcenterMemberByIds(String[] ids) {
        return ucenterMemberMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除会员信息
     *
     * @param id 会员主键
     * @return 结果
     */
    @Override
    public int deleteUcenterMemberById(String id) {
        return ucenterMemberMapper.deleteById(id);
    }

    @Override
    public String login(UcenterMember ucenterMember) {
        LambdaQueryWrapper<UcenterMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UcenterMember::getMobile, ucenterMember.getMobile());
        UcenterMember ucenterMember1 = ucenterMemberMapper.selectOne(queryWrapper);
        if (ucenterMember1 == null) {
            throw new ServiceException("该手机号未注册会员");
        }
        // 对比密码
        if (!SecurityUtils.matchesPassword(ucenterMember.getPassword(), ucenterMember1.getPassword())) {
            throw new ServiceException("密码错误");
        }
        // 判断用户是否被禁用
        if (ucenterMember1.getIsDeleted().equals(DeletedConstants.DELETED) || ucenterMember1.getIsDisabled().equals(DeletedConstants.DELETED)) {
            throw new ServiceException("该账号已被删除/禁用，需回溯请联系管理员");
        }
        // 登录成功则返回封装了用户ID的token
        Map<String, Object> idMap = new HashMap<>(1);
        idMap.put(UserConstants.TOKEN_KEY, ucenterMember1.getId());
        return JwtUtils.createToken(idMap);
    }

    @Override
    public void register(UcenterMember ucenterMember) {
        LambdaQueryWrapper<UcenterMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UcenterMember::getMobile, ucenterMember.getMobile());
        if (count(queryWrapper) > 0) {
            throw new ServiceException("该手机号已被注册");
        }
        // 初始化会员名称
        if (StringUtils.isEmpty(ucenterMember.getNickname())) {
            ucenterMember.setNickname(UserConstants.INIT_NAME);
        }
        // 初始化会员头像
        if (StringUtils.isEmpty(ucenterMember.getAvatar())) {
            ucenterMember.setAvatar(UserConstants.INIT_AVATAR);
        }
        // 密码加密
        ucenterMember.setPassword(SecurityUtils.encryptPassword(ucenterMember.getPassword()));
        // 初始化状态
        ucenterMember.setIsDeleted(DeletedConstants.UN_DELETED);
        ucenterMember.setIsDisabled(DeletedConstants.UN_DELETED);
        if (!save(ucenterMember)) {
            throw new ServiceException("会员注册失败，可能是服务器压力过大，请稍后再试");
        }
    }

    @Override
    public void editPassword(UcenterPwdDto pwdDto) {
        UcenterMember byId = getById(pwdDto.getId());
        if (null == byId) {
            throw new ServiceException("会员不存在");
        }
        // 对比密码
        if (!SecurityUtils.matchesPassword(pwdDto.getOldPwd(), byId.getPassword())) {
            throw new ServiceException("密码错误");
        }
        // 对比通过则更新密码
        byId.setPassword(SecurityUtils.encryptPassword(pwdDto.getNewPwd()));
        if (!updateById(byId)) {
            throw new ServiceException("密码修改失败，请稍后再试");
        }
    }

    @Override
    public boolean updateInfoById(UcenterMember ucenterMember) {
        UcenterMember byId = getById(ucenterMember.getId());
        // 如果会员昵称变更，群发信息通知订单、评论微服务进行对应更新
        if (!byId.getNickname().equals(ucenterMember.getNickname())) {
            // 通知其它微服务更新
            rabbitTemplate.convertAndSend(MqConstants.EDU_EXCHANGE_TOPIC, MqConstants.MEMBER_QUEUE, ucenterMember);
        }
        // 会员信息更新
        return updateById(ucenterMember);
    }
}
